<?php
class Schedule extends NewslettersAppModel {

	var $name = 'Schedule';
	var $useTable = 'schedules';
	var $belongsTo = array('Newsletter'=>
					array('className'=>'Newsletters.Newsletter'));
	CONST COMPLETED = 2;
	CONST SENDING = 1;
	CONST PENDING = 0;
	Const ALL_USER = 1;
	Const SUBSCRIBER_ONLY = 2;
	
	var $SentLog;
	
	function getRecipient($schedule)
	{
		$recipients = array();
		if($schedule[$this->alias]['condition']==self::ALL_USER)
		{
			$allowedModels = cr('Newsletter.allowedModelAlias');
			if(!is_array($allowedModels))
				$allowedModels = (array)$allowedModels;
			foreach($allowedModels as $modelAlias)
			{
				$model = Utility::getModelObject($modelAlias);
				$modelRecipients = $model->find('all',array('fields'=>array('id',$model->displayField,'email'),'recursive'=>-1));
				$modelRecipients = Set::extract('{n}.'.$modelAlias,$modelRecipients);
				foreach($modelRecipients as $key => &$value)
				{
					$displayFieldValue = $value[$model->displayField];
					unset($value[$model->displayField]);
					$value['name'] = $displayFieldValue;
				}
				$recipients = am($recipients,$modelRecipients);
			}
			$subscribes = Cri('Newsletters.Subscriber')->find('all',array('conditions'=>array('not'=>array('email'=>null),'entity'=>null),'fields'=>array('name','email','id')));
			$subscribes =  Set::extract('{n}.Subscriber',$subscribes);
			$recipients = am($recipients,$subscribes);
		} else {
			$subscriberRecipients = Cri('Newsletters.Subscriber')->find('all',array('conditions'=>array('status'=>Subscriber::ACTIVE)));
			$recipients  = Set::extract('{n}.Subscriber',$subscriberRecipients);
		}
		return $recipients;
	}
	
	function logLastActivity($scheduleId)
	{
		$this->id = $scheduleId;
		$this->saveField('last_activity',date('Y-m-d H:i:s'));
	}
	
	function allowNewsletterSend($scheduleId)
	{
		//return true if status is PENDIND or status is pending and it has been 5 hours since any activity.
		return $this->hasAny(array('id'=>$scheduleId,'or'=>array(
			array('status' =>self::PENDING,'date <='=>date('Y-m-d')),'AND'=>array('status'=>self::SENDING,'last_activity < date_sub("'.date('Y-m-d H:i:s').'",INTERVAL 5 hour)')
		)));
	}
	
	function hasSent($scheduleId,$recipient)
	{
		return $this->SentLog->hasSent($scheduleId,$recipient['email']);
	}
	
	function afterInitialize()
	{
		parent::afterInitialize();
		$this->SentLog = cri('Newsletters.SentLog');
	}
	
	function logSend($scheduleId,$recipient)
	{
		return $this->SentLog->logSend($scheduleId,$recipient['email']);
	}
	
	function cleanSendLogs($scheduleId)
	{
		$this->SentLog->cleanUp($scheduleId);
	}
}
?>